package config

import (
	"fmt"
	"github.com/chicken-team-outside/chicken_transmission/client_core/service"
	"sync/atomic"
)

var rpcServerSetting atomic.Value

type RpcServerSetting struct {
	Address string `json:"address"`
	Token   string `json:"token"`
}

func initRpcServerSetting() error {
	cfg := &RpcServerSetting{
		Address: "http://127.0.0.1:8080",
		Token:   "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
	}
	err := service.GetOrSaveConfig([]byte("rpc_server_setting"), cfg)
	if err != nil {
		return fmt.Errorf("failed to get or save rpc server setting: %w", err)
	}
	rpcServerSetting.Store(cfg)
	return nil
}

func RpcServerConfig() *RpcServerSetting {
	return rpcServerSetting.Load().(*RpcServerSetting)
}

func SaveRpcServerSetting(s *RpcServerSetting) error {
	err := service.SaveConfigData([]byte("rpc_server_setting"), s)
	if err == nil {
		rpcServerSetting.Store(s)
	}
	return err
}
